package com.cskaoyan.user.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.CookieUtil;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.TokenJsonBean;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.dto.*;
import com.cskaoyan.user.service.IKaptchaService;


import com.cskaoyan.user.service.ILoginService;
import com.cskaoyan.user.service.IRegisterService;
import com.cskaoyan.user.service.IVerifyService;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * ClassName: UserController
 * Description:
 * date: 2022/6/18 10:09
 *
 * @author bruce
 * @since JDK 8
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    IKaptchaService iKaptchaService;

    @Autowired
    IRegisterService iRegisterService;

    @Autowired
    ILoginService iLoginService;

    @Autowired
    IVerifyService iVerifyService;



    @PostMapping("register")
    public ResponseData userRegister(@RequestBody Map<String, String> map, HttpServletRequest request) {
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");

        //TODO 验证验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String kaptcha_uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse response = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        // String code = response.getImageCode();
        String code = response.getCode();
        if (!code.equals(UserRetCode.SUCCESS.getCode())) {
            //验证失败
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        //向用户表中插入记录
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setUserName(userName);
        userRegisterRequest.setUserPwd(userPwd);
        userRegisterRequest.setEmail(email);
        UserRegisterResponse userRegisterResponse = iRegisterService.register(userRegisterRequest);
        if (userRegisterResponse.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(userRegisterResponse.getMsg());
    }

    @PostMapping("login")
    public ResponseData userLogin(@RequestBody Map<String, String> map, HttpServletRequest request, HttpServletResponse servletResponse) {
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        //验证验证码
        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String kaptcha_uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(kaptcha_uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse response = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        // String code = response.getImageCode();
        String code = response.getCode();
        if (!code.equals(UserRetCode.SUCCESS.getCode())) {
            //验证失败
            return new ResponseUtil<>().setErrorMsg(response.getMsg());
        }
        //验证用户名和密码
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setUserName(userName);
        userLoginRequest.setPassword(userPwd);
        UserLoginResponse userLoginResponse = iLoginService.login(userLoginRequest);

        userLoginResponse.setUsername(userName);
        if (userLoginResponse.getCode().equals(UserRetCode.SUCCESS.getCode())) {
            //登录成功
            //将token传给cookie
            Long uid = userLoginResponse.getId();
            TokenJsonBean tokenJsonBean = new TokenJsonBean(uid, userName);
            String s = JSONObject.toJSON(tokenJsonBean).toString();
            String token = JwtTokenUtils.builder().msg(s).build().creatJwtToken();
            // Cookie cookie = new Cookie("access_token", token);
            Cookie cookie= CookieUtil.genCookie("access_token",token,"/", -1);

            cookie.setHttpOnly(true);
            CookieUtil.setCookie(servletResponse, cookie);
            //参数是否要转换?
            return new ResponseUtil<>().setData(userLoginResponse);
        }
        return new ResponseUtil<>().setErrorMsg(userLoginResponse.getMsg());
    }

    @GetMapping("login")
    public ResponseData userLogin(HttpServletRequest request) {

        //拿到请求头中的cookie
        String access_token = CookieUtil.getCookieValue(request, "access_token");
        if(StringUtils.isEmpty(access_token)){
            return new ResponseUtil<>().setErrorMsg("失败");
        }
        // 从请求头获取userId
        String s = JwtTokenUtils.builder().token(access_token).build().freeJwt();
        TokenJsonBean tokenJsonBean = JSON.parseObject(s, TokenJsonBean.class);
        return new ResponseUtil<>().setData(tokenJsonBean);
    }

    @GetMapping("loginOut")
    public ResponseData userLogOut(HttpServletRequest request, HttpServletResponse response) {
        String access_token = CookieUtil.getCookieValue(request,"access_token");
        if (access_token == null) {
            return new ResponseUtil<>().setErrorMsg(UserRetCode.TOKEN_VALID_FAILED.getMessage());
        }
        //清除token
        // request.setAttribute("access_token",null);
        Cookie cookie = CookieUtil.genCookie("access_token", null, "/", 0);
        cookie.setHttpOnly(true);
        CookieUtil.setCookie(response, cookie);
        return new ResponseUtil<>().setData(null);

    }

    @GetMapping("verify")
    public ResponseData userVerify(String uuid, String username) {
//        String uid = map.get("uid");
//        String username = map.get("username");
        UserVerifyResponse userVerifyResponse = iVerifyService.verify(uuid,username);
        return new ResponseUtil<>().setData(userVerifyResponse);
    }
}
